from django.shortcuts import render
from django_redis import get_redis_connection

from rest_framework import status
from rest_framework.decorators import action

from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response

from rest_framework.views import APIView


from goods.models import SKU
from .models import User

#  注冊要導的包
from rest_framework.generics import CreateAPIView, RetrieveAPIView, UpdateAPIView
from .serializers import RegisterCreateSerializer, UserCenterInfoSerializer, EmailUpdateSerializer, \
    UserHistroySerializer, SKUSerializer, AddressTitleSerializer

from .serializers import AddressesCreateSerializer


class RegisterUsernameCountAPIView(APIView):
    # 獲取用戶名
    def get(self,request,username):

        count = User.objects.filter(username=username)

        data = {
            'count': count,
            'username':username
        }
        return Response(data)


class RegisterPhoneCountAPIView(APIView):
    # 查詢手機號
    def get(self,request,mobile):

        count = User.objects.filter(mobile=mobile).count()
        data = {
            'count':count,
            'phone':mobile
        }

        return Response(data)

class RegisterCreateView(CreateAPIView):
    """
    用户注册    POST /users/
    用户注册我们需要对数据进行校验,同时需要数据入库
    """
    def post(self,request):

        data = request.data
        # 校驗參數
        serializer = RegisterCreateSerializer(data=data)
        serializer.is_valid()

        user = serializer.save()

        from rest_framework_jwt.settings import api_settings
        # 补充生成记录登录状态的token
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)

        # 講token返回
        data = serializer.data
        data['token']  = token
        # user.token = token

        return Response(data)

    serializer_class = RegisterCreateSerializer

# from rest_framework.generics import CreateAPIView
#
# class RegisterCreateView(CreateAPIView):
#
#     serializer_class = RegisterCreateSerializer


from rest_framework.permissions import IsAuthenticated
class UserCenterInfoAPIView(APIView):

    permission_classes = [IsAuthenticated]

    def get(self,request):

        user = request.user

        serializer = UserCenterInfoSerializer(user)
        return Response(serializer.data)

# class UserCenterInfoAPIView(RetrieveAPIView):
#
#     permission_classes = [IsAuthenticated]
#
#     serializer_class = UserCenterIofoSerializer
#
#     def get_object(self):
#         return self.request.user

# # 郵箱驗證
# class EmailUpdateAPIView(APIView):
#
#     permission_classes = [IsAuthenticated]
#
#     def put(self,request):
#         data = request.data
#         user = request.user
#
#         serializer = EmailUpdateSerializer(instance=user,data=data)
#         serializer.is_valid(raise_exception=True)
#
#         serializer.save()
#
#         # 發送鏈接
#         from django.core.email import send_mail
#         subject = '美多商场激活邮件'
#         message = ''
#         from_email = '美多商城<m18236417889@163.com>'
#         email = request.data.get('email')
#         recipient_list = [email]
#
        # verify_url = generic_verify_url(request.user.id, email)
#
#         html_message = '<p>尊敬的用户您好！</p>' \
#                        '<p>感谢您使用美多商城。</p>' \
#                        '<p>您的邮箱为：%s 。请点击此链接激活您的邮箱：</p>' \
#                        '<p><a href="%s">%s<a></p>' % (email, verify_url, verify_url)
#         send_mail(subject=subject,
#                   message=message,
#                   from_email=from_email,
#                   recipient_list=recipient_list,
#                   html_message=html_message)
#
#
#         return Response(serializer.data)

# class EmailUpdateAPIView(APIView):
#
#     permission_classes = [IsAuthenticated]
#
#     def put(self,request):
#         data = request.data
#         user = request.user
#
#         serializer = EmailUpdateSerializer(instance=user,data=data)
#         serializer.is_valid(raise_exception=True)
#
#         serializer.save()
#
#         # 發送鏈接
#         from django.core.email import send_mail
#         subject = '美多商场激活邮件'
#         message = ''
#         from_email = '美多商城<m18236417889@163.com>'
#         email = request.data.get('email')
#         recipient_list = [email]
#
#         verify_url = generic_verify_url(request.user.id, email)
#
#         html_message = '<p>尊敬的用户您好！</p>' \
#                        '<p>感谢您使用美多商城。</p>' \
#                        '<p>您的邮箱为：%s 。请点击此链接激活您的邮箱：</p>' \
#                        '<p><a href="%s">%s<a></p>' % (email, verify_url, verify_url)
#         send_mail(subject=subject,
#                   message=message,
#                   from_email=from_email,
#                   recipient_list=recipient_list,
#                   html_message=html_message)
#
#
#         return Response(serializer.data)

class EmailUpdateAPIView(UpdateAPIView):
    permission_classes = [IsAuthenticated]
    serializer_class = EmailUpdateSerializer

    def get_object(self):
        return self.request.user


class VerificationEmailView(APIView):
    """
    验证激活邮箱
    GET /users/emails/verification/?token=xxxx

    思路:
    获取token,并判断
    获取 token中的id
    查询用户,并判断是否存在
    修改状态
    返回响应
    """

    def get(self,request):
        # 获取token, 并判断
        token = request.query_params.get('token')
        if not token:
            return Response({'message':'缺少token'},status=status.HTTP_400_BAD_REQUEST)
        # 获取token中的id,email
        # 查询用户, 并判断是否存在
        from users.utils import check_verify_email_token
        user = check_verify_email_token(token)
        if user is None:
            return Response({'message':'链接无效'},status=status.HTTP_400_BAD_REQUEST)
        else:
            # 修改状态
            user.email_active = True
            user.save()
            # 返回响应
            return Response({'message':'ok'})


# class AddressesCreateAPIView(APIView):
#
#     permission_classes = [IsAuthenticated]
#
#     def post(self,request):
#         # request.user
#
#         # 1.接收数据
#         # request.data 是没有 user信息的
#         data = request.data
#         # 2.验证数据
#         serializer = AddressesCreateSerializer(data=data,context={'request':request})
#         # 3.数据入库
#         serializer.is_valid(raise_exception=True)
#         serializer.save()
#         # 4.返回相应
#         return Response(serializer.data)

from rest_framework import mixins
from rest_framework.viewsets import GenericViewSet
class AddressViewSet(mixins.ListModelMixin,mixins.CreateModelMixin,mixins.UpdateModelMixin,GenericViewSet):

    serializer_class = AddressesCreateSerializer
    permission_classes = [IsAuthenticated]

    def get_queryset(self):
        return self.request.user.addresses.filter(is_deleted=False)

    def create(self,request,*args,**kwargs):
        count = request.user.addresses.count()

        if count >= 20:
            return Response({'message':'保存數量已經達到上限'},status=status.HTTP_400_BAD_REQUEST)

        return super().create(request,*args,**kwargs)

    def list(self,request,*args,**kwargs):
        queryset = self.get_queryset()
        serializer = self.get_serializer(queryset,many=True)
        user = self.request.user

        return Response({
            'user_id':user.id,
            'default_address_id':user.default_address_id,
            'limit':20,
            'addresses':serializer.data,
        })

    def destroy(self, request, *args, **kwargs):
        """
        处理删除
        """
        address = self.get_object()

        # 进行逻辑删除
        address.is_deleted = True
        address.save()

        return Response(status=status.HTTP_204_NO_CONTENT)


    @action(methods=['put'], detail=True)
    def status(self, request, pk=None, address_id=None):
        """
        修改标题
        """
        address = self.get_object()
        serializer = AddressTitleSerializer(instance=address, data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(serializer.data)

    @action(methods=['put'], detail=True)
    def status(self, request, pk=None, address_id=None):
        """
        设置默认地址
        """
        address = self.get_object()
        request.user.default_address = address
        request.user.save()
        return Response({'message': 'OK'}, status=status.HTTP_200_OK)


class UserHistoryAPIView(CreateAPIView):


    permission_classes = [IsAuthenticated]

    serializer_class = UserHistroySerializer

    def get(self,request):

        user = request.user

        redis_conn = get_redis_connection('history')
        ids = redis_conn.lrange('history_%s'%user.id,0,4)

        skus = []

        for sku_id in ids:

            sku = SKU.objects.get(pk=sku_id)
            skus.append(sku)

        serializer = SKUSerializer(skus,many=True)

        return Response(serializer.data)

from rest_framework_jwt.views import ObtainJSONWebToken
from cart.utils import merge_cookie_to_redis

class UserAuthorizationView(ObtainJSONWebToken):

    def post(self, request):
        # 调用jwt扩展的方法，对用户登录的数据进行验证
        response = super().post(request)

        # 如果用户登录成功，进行购物车数据合并
        serializer = self.get_serializer(data=request.data)
        if serializer.is_valid():
            # 表示用户登录成功
            user = serializer.validated_data.get("user")
            # 合并购物车
            #merge_cart_cookie_to_redis(request, user, response)
            response = merge_cookie_to_redis(request, user, response)

        return response

